package com.xiaomi.shoppinglist

import android.appwidget.AppWidgetManager
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import android.util.Log

class MainActivity : AppCompatActivity() {
    private val TAG = "MainActivity"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // 初始化数据库
        ShoppingListDatabase.init(this)

        // 设置添加购物项按钮点击事件
        findViewById<Button>(R.id.add_item_button).setOnClickListener {
            startActivity(Intent(this, AddItemActivity::class.java))
        }

        // 设置添加到桌面按钮点击事件
        findViewById<Button>(R.id.add_to_home_button).setOnClickListener {
            addWidgetToHomeScreen()
        }
    }

    private fun addWidgetToHomeScreen() {
        Log.d(TAG, "Adding widget to home screen")
        val intent = Intent(AppWidgetManager.ACTION_APPWIDGET_PICK)
        val appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID
        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
        startActivityForResult(intent, REQUEST_ADD_WIDGET)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_ADD_WIDGET && resultCode == RESULT_OK) {
            // 小部件添加成功
            Log.d(TAG, "Widget added successfully")
        }
    }

    companion object {
        private const val REQUEST_ADD_WIDGET = 1
    }
}